package com.action.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.action.childbase.ChildBaseActivity;
import com.action.service.pressenter.SelectCurrentLocationPresenter;
import com.action.ui.adapter.SearchAdapter;
import com.action.ui.adapter.ShowHisLocationAdapter;
import com.action.ui.view.EditSearchView;
import com.action.utils.LocUtils;
import com.action.utils.SingleClick;
import com.base.app_core.View.dialog.SelectRegionWindow;
import com.base.app_core.base.ActionPacketView;
import com.base.app_core.model.PoiList;
import com.base.app_core.model.Region;
import com.base.app_core.model.dto.LocationDto;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.XYBAUtils;
import com.base.app_core.util.DialogHelper;
import com.blankj.utilcode.util.StringUtils;
import com.xinglai.yun.R;
import com.tencent.map.geolocation.TencentLocation;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

public class SelectedCurrentLocationActivity extends
        ChildBaseActivity<SelectCurrentLocationPresenter> implements ActionPacketView.onPoiResult, SelectRegionWindow.OnRegionSelectListener {

    private static final int INIT_MSG_LOCATION = 0x01;
    @Inject
    LocUtils locUtils;

    @BindView(R.id.clearEditText)
    EditSearchView editSearchView;

    @BindView(R.id.city)
    TextView city;

    @BindView(R.id.city_location)
    TextView topRightEdit;

    @BindView(R.id.address)
    TextView address;

    @BindView(R.id.ry)
    RecyclerView ry;

    @BindView(R.id.ll_his)
    LinearLayout ll_his;

    @Inject
    LocationDto locationDto;

    private String searchText = "";

    private TencentLocation location;

    final List<PoiList> items = new ArrayList<>();

    private SearchAdapter searchAdapter;
    private ShowHisLocationAdapter hisLocationAdapter;
    private SelectRegionWindow regionWindow;
    private Handler handler;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_selected_current_location;
    }

    @Override
    protected void initView() {
        super.initView();
        setToolBar("当前位置");
        locationDto = getIntent().getParcelableExtra(AppConstants.EXTRA.LOCATION_INFO);
        if (locationDto == null) {
            finish();
            return;
        }

        handler = new Handler(getMainLooper(), new Handler.Callback() {
            int count = 0;

            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case INIT_MSG_LOCATION:
                        if (count == 0) {
                            city.setText("定位中");
                        } else if (count == 1) {
                            city.setText("定位中.");
                        } else if (count == 2) {
                            city.setText("定位中..");
                        } else if (count == 3) {
                            city.setText("定位中...");
                            count = 0;
                        }
                        count++;
                        handler.sendEmptyMessageDelayed(INIT_MSG_LOCATION, 600);
                        break;
                }
                return false;
            }
        });
        initLocaitonAction();
        initCityInfo();
    }

    private void initLocaitonAction() {
        locUtils.requestLocation(this);
        handler.sendEmptyMessage(INIT_MSG_LOCATION);
        address.setVisibility(View.GONE);
        locUtils.setOnLocationLisener(new LocUtils.LocationLisener() {

            @Override
            public void onLocationSuccess(TencentLocation location) {
                SelectedCurrentLocationActivity.this.location = location;
                address.setVisibility(View.VISIBLE);
                city.setVisibility(View.VISIBLE);
                city.setText(location.getName());
                address.setText(location.getAddress());
                handler.removeMessages(INIT_MSG_LOCATION);
            }

            @Override
            public void onLocationFailure(int error, String reason) {
                showToast(reason);
            }
        });

    }

    private void initCityInfo() {
        topRightEdit.setText(locationDto.getCity());
        topRightEdit.setTextColor(getResources().getColor(R.color.text_black));
        topRightEdit.setVisibility(View.VISIBLE);
        topRightEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!regionWindow.isShowing()) {
                    regionWindow.show(topRightEdit);
                }
            }
        });

        showRegionWindow();

        //初始化历史位置布局
        final List<PoiList> poiLists = mPresenter.selectHisLocData();
        if (!XYBAUtils.isEmpty(poiLists)) {
            initHisLayoutVisible(View.VISIBLE);
        } else {
            initHisLayoutVisible(View.GONE);
        }

        ry.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        hisLocationAdapter = new ShowHisLocationAdapter();
        hisLocationAdapter.setHistoryHandlerInterface(new ShowHisLocationAdapter.onLocationSeleted() {
            @Override
            public void onSeleted(PoiList item) {
                fillDtoAndBack(item);
            }
        });
        ry.setAdapter(hisLocationAdapter);
        hisLocationAdapter.notifyDataSetChanged(poiLists);


//        初始化搜索
        searchAdapter = new SearchAdapter(this, items, searchText);
        editSearchView.setAdapter(searchAdapter);

        editSearchView.setOnQueryTextListener(new EditSearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String var1) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String searchText) {
                String temp = searchText.toString();
                if (StringUtils.isEmpty(temp)) {
                    return false;
                }

                if (SingleClick.isSingle()) {
                    mPresenter.getPoiList(temp, locationDto.getCity());
                    SelectedCurrentLocationActivity.this.searchText = searchText;
                }

                return false;
            }
        });

        editSearchView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                PoiList item = searchAdapter.getItem(position);
                if (item == null) {
                    return;
                }

                List<PoiList> list = hisLocationAdapter.getList();
                list.add(item);
                hisLocationAdapter.notifyDataSetChanged();
                initHisLayoutVisible(View.VISIBLE);

                mPresenter.insertHistoryLocation(item);
                editSearchView.closeSearch();
                searchAdapter.setData(null);
                fillDtoAndBack(item);
            }
        });

    }

    private void fillDtoAndBack(PoiList item) {
        PoiList.AdInfoBean ad_info = item.getAd_info();
        if (ad_info != null) {
            locationDto.setCity(ad_info.getCity());
            locationDto.setDistrict(ad_info.getDistrict());
            locationDto.setProvince(ad_info.getProvince());
            locationDto.initCityCode(String.valueOf(ad_info.getAdcode()));
        }
        PoiList.LocationBean location = item.getLocation();
        if (location != null) {
            locationDto.setLatitude(location.getLat());
            locationDto.setLongitude(location.getLng());
        }

        locationDto.setName(item.getTitle());
        locationDto.setAddress(item.getAddress());
        back();
    }

    private void back() {
        Intent intent = new Intent();
        intent.putExtra(AppConstants.EXTRA.LOCATION_INFO, locationDto);
        setResult(RESULT_OK, intent);
        finish();
    }

    private void showRegionWindow() {
        if (regionWindow == null) {
            regionWindow = new SelectRegionWindow(this);
            regionWindow.setSelectDeep(2);
            regionWindow.init();
            regionWindow.setOnRegionSelectListener(this);
        }
    }

    private void initHisLayoutVisible(int gone) {
        ll_his.setVisibility(gone);
        ry.setVisibility(gone);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locUtils != null) {
            locUtils.setOnLocationLisener(null);
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    @Override
    protected String[] getPermissions() {
        return new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
    }


    @OnClick({R.id.refresh, R.id.clear, R.id.location_cl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.refresh:
                initLocaitonAction();
                break;
            case R.id.location_cl:
                if (location == null) {
                    showToast("当前没有定位信息,请刷新定位");
                    return;
                }
                locationDto.setCity(location.getCity());
                locationDto.setDistrict(location.getDistrict());
                locationDto.setProvince(location.getProvince());
                locationDto.setLatitude(location.getLatitude());
                locationDto.setLongitude(location.getLongitude());
                locationDto.setName(location.getName());
                locationDto.setAddress(location.getAddress());
                locationDto.initCityCode(location.getCityCode());
                back();
                break;
            case R.id.clear:
                DialogHelper.showSelectOkCancel(this, "确定清空历史搜索吗?", "确认", "取消", new DialogHelper.onItemClickLisener() {
                    @Override
                    public void onItemClick(boolean position) {
                        if (position) {
                            mPresenter.clearHisLocData();
                            hisLocationAdapter.clear();
                            hisLocationAdapter.notifyDataSetChanged();
                            initHisLayoutVisible(View.GONE);
                        }
                    }
                });
                break;
        }
    }

    @Override
    public void onPoiSuccess(List<PoiList> poiList) {
        if (poiList == null || poiList.isEmpty()) {
            editSearchView.closeSearch();
            editSearchView.initCloseView(false);
            return;
        }
        editSearchView.initCloseView(true);
        editSearchView.showSearch(true);
        searchAdapter.setData(poiList);
    }

    @Override
    public void onSelectRegion(Region province, Region city, Region district) {
        if (topRightEdit != null) {
            topRightEdit.setText(city.getName());
            locationDto.setCity(city.getName());
        }
    }
}
